<template>
  <div :class="fullScreen ? 'templePage-wrapper fullScreen' : 'templePage-wrapper'">
    <div class="title-wrapper">
      <span class="title">{{ title }}</span>
      <div class="buttons-wrapper">
        <el-tooltip class="item" effect="dark" placement="top-start">
          <div slot="content">
            @@pageId：当前页面
            <br />@@controlId：当前控件 <br />@@deptId：当前部门
            <br />@@userId：当前用户
            <br />
          </div>
          <span class="icon iconfont iconkuangjia-zhichi"></span>
        </el-tooltip>
        <el-tooltip v-if="!fullScreen" class="item" effect="dark" content="全屏" placement="top-start">
          <span @click="handleFullScreen" class="icon iconfont iconquanping"></span>
        </el-tooltip>
        <el-tooltip v-if="fullScreen" class="item" effect="dark" content="退出全屏" placement="top-start">
          <span @click="handleFullScreen" class="icon iconfont">&#xe66d;</span>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="预览" placement="top-start">
          <span class="icon iconfont iconlogin_icon_password_hide" @click="perview"></span>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="保存" placement="top-start">
          <span class="icon iconfont iconbiaoge-baocun" @click="save"></span>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="关闭" placement="top-start">
          <span class="icon iconfont iconbiaoqianlan-guanbi" @click="cancel"></span>
        </el-tooltip>
      </div>
    </div>
    <div class="configPageContent-wrapper">
      <!-- 左侧组件列表 -->
      <div class="components-wrapper">
        <div class="row">
          <span>检索组件</span>
          <draggable class="components-draggable" :list="inputComponents"
            :group="{ name: 'searchesGroup', pull: 'clone', put: false }" :clone="cloneComponent"
            draggable=".components-item" :sort="false" @end="onEnd">
            <div class="components-item" v-for="(element, index) in inputComponents" :key="index">
              <div class="components-body">{{ element.label }}</div>
            </div>
          </draggable>
        </div>
        <div class="row">
          <span>按钮组件</span>
          <draggable class="components-draggable" :list="buttonComponents"
            :group="{ name: 'buttonsGroup', pull: 'clone', put: false }" :clone="cloneComponent"
            draggable=".components-item" :sort="false" @end="onEnd">
            <div v-for="(element, index) in buttonComponents" :key="index" class="components-item">
              <div class="components-body">{{ element.label }}</div>
            </div>
          </draggable>
        </div>
        <div class="row" v-show="false">
          <span>统计组件</span>
          <draggable class="components-draggable" :list="statisticalComponents"
            :group="{ name: 'statisticalGroup', pull: 'clone', put: false }" :clone="cloneComponent"
            draggable=".components-item" :sort="false" @end="onEnd">
            <div v-for="(element, index) in statisticalComponents" :key="index" class="components-item">
              <div class="components-body">{{ element.label }}</div>
            </div>
          </draggable>
        </div>
      </div>
      <!-- 中间操作界面 -->
      <div class="board-wrapper">
        <el-form :size="formConf.size" :label-position="formConf.labelPosition" :disabled="formConf.disabled"
          :label-width="formConf.labelWidth + 'px'">
          <draggable class="drawing-board" :list="drawingList" :animation="340">
            <draggable-item v-for="(element, index) in drawingList" :key="element.renderKey" :drawing-list="drawingList"
              :element="element" :index="index" :form-conf="formConf" :active-id="activeId" :group="element.group"
              @activeItem="activeFormItem" @copyItem="drawingItemCopy" @deleteItem="drawingItemDelete" />
          </draggable>
        </el-form>
        <!-- TODO 自定义表头DIV -->
        <div id="x-spreadsheet"></div>
      </div>
      <!-- 右侧组件属性 -->
      <div class="componentsProperty-wrapper">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="页面配置" name="pageInfo">
            <el-form class="systemForm" label-width="100px" label-position="left" :model="pageInfo" ref="form">
              <el-form-item label="页面名称:">
                <el-input class="systemInput" v-model="pageInfo.text"></el-input>
              </el-form-item>
              <el-form-item label="图标:">
                <el-input class="systemInput" v-model="pageInfo.icon"></el-input>
              </el-form-item>
              <el-form-item label="页面编码:">
                <el-input class="systemInput" v-model="pageInfo.code"></el-input>
              </el-form-item>
              <el-form-item label="应用类型：">
                <el-select class="systemInput" v-model="pageInfo.type">
                  <el-option v-for="item in pageTypeMap" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="应用模板：">
                <el-select class="systemInput" v-model="pageInfo.template" @change="templateChange">
                  <el-option v-for="item in templateMap" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="请求地址:">
                <el-input class="systemInput" v-model="pageInfo.url"></el-input>
              </el-form-item>
              <el-form-item label="数据源:">
                <el-select v-model="moreDataSourceValue" placeholder="请选择" @change="dataSorceChange">
                  <el-option v-for="item in moreDataSource" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="关联表：">
                <el-select class="systemInput" v-model="tableInfo" value-key="id" filterable @change="tableChange">
                  <el-option v-for="item in tableList" :key="item.id" :value="item" :label="item.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="主键:">
                <el-input class="systemInput" v-model="pageInfo.primaryName"></el-input>
              </el-form-item>
              <!-- TODO 新增脚本 -->
              <el-form-item label="初始化脚本:">
                <el-input class="systemInput" v-model="pageInfo.initJs" @focus="systemInputFocus('initScript')">
                </el-input>
              </el-form-item>
              <el-form-item label="sql语句:">
                <el-input class="systemInput" v-model="pageInfo.sql" type="textarea" :rows="6"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="组件配置" name="componentInfo">
            <!-- 检索组件属性 -->
            <el-form class="systemForm" label-width="80px" label-position="left" v-if="activeData.type !== 'button' && activeData.type !== 'flowButton'
              ">
              <el-form-item label="标签名:">
                <el-input class="systemInput" v-model="activeData.label"></el-input>
              </el-form-item>
              <el-form-item label="标签宽度:">
                <el-input class="systemInput" v-model="activeData.labelWidth">
                  <template slot="append">px</template>
                </el-input>
              </el-form-item>
              <el-form-item label="组件宽度:">
                <el-input class="systemInput" v-model="activeData.width">
                  <template slot="append">px</template>
                </el-input>
              </el-form-item>
              <el-form-item label="占位提示:">
                <el-input class="systemInput" v-model="activeData.placeholder"></el-input>
              </el-form-item>
              <el-form-item label="默认值:">
                <el-input class="systemInput" v-model="activeData.defaultValue"></el-input>
              </el-form-item>
              <el-form-item label="数据源:">
                <el-select v-model="activeData.executeDb" placeholder="请选择">
                  <el-option v-for="item in dataSourceOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="能否清空:" v-if="activeData.renderer === 'Select'">
                <el-switch v-model="activeData.clearable"></el-switch>
              </el-form-item>
              <el-form-item label="编码:">
                <el-input class="systemInput" v-model="activeData.code"></el-input>
              </el-form-item>
              <el-form-item label="双击事件:">
                <el-input class="systemInput" v-model="methodName"
                  @dblclick.native="handleComSelect('comConfig', null)"></el-input>
              </el-form-item>
              <el-form-item label="数据类型:">
                <el-select class="systemInput" v-model="activeData.extattr" placeholder="请选择类型" clearable>
                  <el-option v-for="item in selectControlType" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="查询字段:" v-if="activeData.type">
                <el-input class="systemInput" v-model="activeData.attr"></el-input>
              </el-form-item>
              <el-form-item label="参照列:" v-if="activeData.type">
                <el-select clearable class="systemInput" v-model="activeData.refer" placeholder="请选择参照列"
                  @visible-change="handleReferChange">
                  <el-option v-for="item in selectComponents" :key="item.code" :label="item.label" :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否显示:">
                <el-switch v-model="activeData.show" active-color="rgba(0,128,255,1)" inactive-color="#ff4949">
                </el-switch>
              </el-form-item>
              <el-form-item label="请求类型" v-if="activeData.renderer === 'Select'">
                <el-select class="systemInput" v-model="activeData.dataType" placeholder="请选择类型" @change="selectChange">
                  <el-option v-for="item in dataTypeMap" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="请求地址:" v-if="activeData.renderer === 'Select' && activeData.dataType !== 2
                ">
                <el-input class="systemInput" v-model="activeData.url"></el-input>
              </el-form-item>
              <el-form-item label="自定义:" v-if="activeData.renderer === 'Select' && activeData.dataType === 2
                ">
                <el-input class="systemInput" v-model="activeData.data" type="textarea" :rows="6"></el-input>
              </el-form-item>
              <el-form-item label="键:" v-if="activeData.renderer === 'Select' && activeData.dataType === 1
                ">
                <el-input class="systemInput" v-model="activeData.data.key"></el-input>
              </el-form-item>
              <el-form-item label="值:" v-if="activeData.renderer === 'Select' && activeData.dataType === 1
                ">
                <el-input class="systemInput" v-model="activeData.data.value"></el-input>
              </el-form-item>
              <el-form-item label="键:" v-if="activeData.renderer === 'Select' && activeData.dataType === 3
                ">
                <el-input class="systemInput" v-model="activeData.data"></el-input>
              </el-form-item>
              <el-form-item label="sql语句" v-if="activeData.renderer === 'Select' && activeData.dataType === 3
                ">
                <el-input class="systemInput" v-model="activeData.sql" type="textarea" :rows="6"></el-input>
              </el-form-item>
            </el-form>
            <!-- 按钮组件属性 -->
            <el-form class="systemForm" label-width="80px" label-position="left" v-if="activeData.type == 'button'">
              <el-form-item label="按钮类型:">
                <el-select class="systemInput" v-model="activeData.attr" placeholder="请选择类型" @change="buttonChange">
                  <el-option v-for="item in buttonControlType" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="按钮名称:">
                <el-input class="systemInput" v-model="activeData.defaultValue"></el-input>
              </el-form-item>
              <el-form-item label="按钮编码:">
                <el-input class="systemInput" v-model="activeData.code"></el-input>
              </el-form-item>
              <el-form-item label="请求类型:" v-show="false">
                <!-- v-if="activeData.attr === 'businessButtonCustom'" -->
                <el-select class="systemInput" v-model="activeData.contentType">
                  <el-option v-for="item in contentTypeMap" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="请求地址:" v-show="false">
                <!-- v-if="activeData.attr === 'businessButtonCustom'" -->
                <el-input class="systemInput" v-model="activeData.url"></el-input>
              </el-form-item>
              <el-form-item label="请求参数:" v-show="false">
                <!-- v-if="activeData.attr === 'businessButtonCustom'"  @focus="systemInputFocus('params')"-->

                <el-input class="systemInput" v-model="activeData.params"></el-input>
              </el-form-item>

              <el-form-item label="窗体类型:" v-show="false">
                <!-- v-if="activeData.attr === 'businessButtonCustom'" -->
                <el-select v-model="activeData.formType" clearable @change="windowTypeMapChange">
                  <el-option v-for="item in windowTypeMap" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="关联窗体:" v-show="false">
                <!-- v-show="windowTypeMapShow" v-if="activeData.attr === 'businessButtonCustom'" -->
                <el-input class="systemInput" v-model="methodName" placeholder="请选择窗体"
                  @dblclick.native="handleComSelect('comConfig', null)"></el-input>
              </el-form-item>
              <!-- 是否多选  chooseMore;//是否多选，0否 、1是 -->
              <el-form-item label="是否多选:" label-width="80px" v-show="false">
                <!-- v-if="activeData.attr === 'businessButtonCustom'" -->
                <el-select class="systemInput" v-model="relatedPageInfo.multipleChoice">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- TODO 新增脚本 -->
              <el-form-item label="脚本:" label-width="80px">
                <el-input type="textarea" :rows="6" v-model="activeData.sql"
                  @focus="systemInputFocus('scriptStatements')"></el-input>
              </el-form-item>
            </el-form>
            <!-- 流程按钮组件属性 -->
            <el-form class="systemForm" label-width="80px" label-position="left" v-if="activeData.type == 'flowButton'">
              <el-form-item label="按钮类型:">
                <el-select class="systemInput" v-model="activeData.attr" placeholder="请选择类型" @change="flowButtonChange">
                  <el-option v-for="item in flowButtonType" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="按钮名称:">
                <el-input class="systemInput" v-model="activeData.defaultValue"></el-input>
              </el-form-item>
              <el-form-item label="按钮编码:">
                <el-input class="systemInput" v-model="activeData.code"></el-input>
              </el-form-item>
              <el-form-item label="请求地址:">
                <el-input class="systemInput" v-model="activeData.url"></el-input>
              </el-form-item>
              <el-form-item label="sql语句:">
                <el-input class="systemInput" v-model="activeData.sql" type="textarea" :rows="6"></el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <!-- 表头配置 -->
          <el-tab-pane label="表头配置" name="tableCellInfo">
            <el-form class="systemForm" label-width="85px" label-position="left">
              <el-form-item label="列宽:">
                <el-input class="systemInput" v-model="tableCellInfo.width"></el-input>
              </el-form-item>
              <el-form-item label="列名:">
                <el-input class="systemInput" v-model="tableCellInfo.text"></el-input>
              </el-form-item>
              <el-form-item label="键值:">
                <el-input class="systemInput" v-model="tableCellInfo.prop"></el-input>
              </el-form-item>
              <el-form-item label="类型:">
                <el-select v-model="cellTypeValue" value-key="value" placeholder="请选择" @change="columSelectChange">
                  <el-option v-for="item in cellTypeOptions" :key="item.value" :label="item.label" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="图标:" v-show="coloumTypeValue == '3'">
                <el-input class="coloumType" v-model="tableCellInfo.iconClass"
                  @dblclick.native="handleComSelect('headConfig', 'icon')"></el-input>
              </el-form-item>
              <!-- TODO 新增表头配置加入超链接 -->
              <el-form-item label="事件类型:" v-show="false">
                <el-select v-model="eventTypeValue" placeholder="请选择">
                  <el-option v-for="item in eventTypeOptions" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="事件内容:" v-show="false">
                <!-- v-model="headMethodName" -->
                <el-input class="systemInput" v-model="tableCellInfo.eventContentHeader" @dblclick.native="
                  handleComSelect('headConfig', tableCellInfo)
                  " clearable readonly></el-input>
              </el-form-item>
              <el-form-item label="时间格式:">
                <el-select class="systemInput" v-model="tableCellInfo.timeFormat" clearable allow-create filterable>
                  <el-option v-for="item in timeType" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="脚本:">
                <el-input class="systemInput" type="text" v-model="tableCellInfo.sql"
                  @focus="systemInputFocus('tableScript')"></el-input>
              </el-form-item>
              <el-form-item label="键值对:" style="heigh: 120px !important">
                <el-input class="systemInput" v-model="tableCellInfo.options" type="textarea" :rows="6"
                  placeholder='[{"value":"-1","label":"已作废","color":"#939599"},{"value":"0","label":"未上报","color":"#ffaa00"},{"value":"1","label":"流程中","color":"#0080ff"},{"value":"2","label":"已完成","color":"#52cc14"}]'>
                </el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 预览 -->
    <template-page v-if="dialogFormVisible" :perviewPageContent="pageInfo" @perviewPageClose="handlePerviewPage">
    </template-page>
    <!-- 检索组件 双击事件 配置弹窗 -->
    <div class="maskCenter comSelect-wrapper" v-if="comSelectShow">
      <div class="systemDialog" style="width: 650px; height: 667px">
        <div class="dialog-header" v-winmove>
          <span>组件选择</span>
        </div>
        <div class="dialog-body">
          <div class="components-wrapper">
            <el-tabs>
              <el-tab-pane label="系统组件">
                <el-checkbox-group v-model="checkedCom" @change="handleComCheck">
                  <el-checkbox class="systemCheckbox" v-for="item in systemComList" :label="item.id" :key="item.id">{{
                    item.text }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-tab-pane>
              <el-tab-pane label="自定义页面">
                <el-input placeholder="请输入组件名称" class="systemInput" v-model="comName" @change="getCustomPageList">
                  <el-button slot="append" icon="el-icon-search" @click="getCustomPageList"></el-button>
                </el-input>
                <el-checkbox-group v-model="checkedCom" @change="handleComCheck">
                  <el-checkbox class="systemCheckbox" v-for="item in pageList" :key="item.id" :label="item.id">{{
                    item.text }}
                  </el-checkbox>
                </el-checkbox-group>
              </el-tab-pane>
            </el-tabs>
          </div>
          <el-input class="systemInput params" placeholder="参数格式" v-model="comDataParamsString"></el-input>
          <el-input class="systemInput params" placeholder="返回格式" v-model="comDataReturnString"></el-input>
        </div>
        <div class="dialog-footer right">
          <span class="systemButtonConfirm" @click="comSelectConfirm">确定</span>
          <span class="systemButtonCancel" @click="comSelectShow = false">取消</span>
        </div>
      </div>
    </div>

    <el-dialog v-dialogDrag :title="systemInputDialogType == 'scriptStatements' ? '脚本编辑器' : '脚本编辑器'"
      :visible="systemInputDialogVisible" width="85%" :close-on-press-escape="true" append-to-body :show-close="true"
      @close="systemInputDialogVisible = false">
      <winComSelect v-if="relatedPageShow" :pcomevents="pcomeventsData" :columnValue="coloumTypeValueSend"
        @close="closeWinCom" @ok="saveWinCom"></winComSelect>
      <div>
        <el-button type="text" @click="relatedPageShow = true">选择组件</el-button>
        <el-input v-model="componnetContent"></el-input>
        <el-button type="primary" plain @click="codeFormatte" style="margin-left: 20px;">格式化</el-button>
      </div>
      <div>
        <el-row :gutter="20">
          <el-col :span="18">
            <div style="height:450px">
              <codeMirrorIDE ref="codeMirrorIDERef" style="overflow-y: auto;height:100%;width:100%"></codeMirrorIDE>
            </div>
          </el-col>
          <el-col :span="6">
            <div style="border-left-width:1px;border-left-style:solid;border-left-color:black;padding-left:5px">
              <funTree @write="writeScp" />
            </div>
          </el-col>
        </el-row>
      </div>

      <span slot="footer" class="dialog-footer">

        <el-button type="primary" @click="systemInputDialogFun(1)">确 定</el-button>
        <el-button @click="systemInputDialogFun(0)">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { pageSave, pageDetail, pageQuery } from "@/system/api/customPage";
import { tableList, columnList } from "@/system/api/listStructure";
import Draggable from "vuedraggable";
import {
  formConf,
  inputComponents,
  buttonComponents,
  statisticalComponents,
  fun,
} from "./generator/config";
import DraggableItem from "./draggableItem";
import TemplatePage from "./templatePage";
import Spreadsheet from "x-data-spreadsheet";
import winmove from "@/directives/winmove";
import zhCN from "x-data-spreadsheet/src/locale/zh-cn";
import winComSelect from "@/system/components/winComSelect.vue";
import Vue from "vue";
//新增数据源下拉框组件,和busJS
import {
  getMoreDataSource,
  getDataSourceById,
  getTableListByDataSourcId,
} from "@/system/api/public";
Spreadsheet.locale("zh-cn", zhCN);

let tempActiveData;

import codeMirrorCom from '@/system/components/codeMirrorCom'
import codeMirrorIDE from '@/system/components/codeMirrorIDE'
import funTree from '@/system/pages/customPage/funTree.vue'

export default {
  data() {
    return {
      title: "新增页面",
      idGlobal: 3,
      formConf,
      inputComponents,
      buttonComponents,
      statisticalComponents,
      chooseMore: 0,
      drawingList: [
        // {
        //   layout: "rowFormItem",
        //   tag: "row",
        //   class: "row",
        //   formId: 1,
        //   group: "statisticalGroup",
        //   label: "统计区",
        //   code: "statistical",
        //   type: "div",
        //   children: [],
        //   componentName: "统计区",
        //   style: { height: "30%" },
        //   class: "statisticalGroup",
        // },
        {
          layout: "rowFormItem",
          tag: "row",
          class: "row",
          formId: 2,
          group: "searchesGroup",
          label: "检索区",
          code: "search",
          type: "div",
          children: [],
          componentName: "检索区",
          style: { height: "30%" },
          class: "searchesGroup",
        },
        {
          layout: "rowFormItem",
          tag: "row",
          class: "row",
          formId: 3,
          group: "buttonsGroup",
          label: "按钮区",
          code: "button",
          type: "div",
          children: [],
          componentName: "按钮区",
          class: "buttonsGroup",
          style: { height: "30%" },
        },
      ],
      activeData: {},
      headActivData: {}, //TODO 表头
      activeId: "",
      fullScreen: false,
      dialogFormVisible: false,
      originTable: {},
      activeTab: "pageInfo",
      pageInfo: {
        url: "/page/record?pageId=@@pageId",
        sql: "",
      },
      tableHeaderInfo: {},
      tableCellInfo: {},
      // 关联表
      tableInfo: {},
      selectControlType: [
        { value: "date", label: "日期（相等）" },
        { value: "date_ge", label: "日期（大于等于）" },
        { value: "date_le", label: "日期（小于等于）" },
        { value: "date_gt", label: "日期（大于）" },
        { value: "date_lt", label: "日期（小于）" },
        { value: "datetime", label: "日期时间（相等）" },
        { value: "datetime_ge", label: "日期时间（大于等于）" },
        { value: "datetime_le", label: "日期时间（小于等于）" },
        { value: "datetime_gt", label: "日期时间（大于）" },
        { value: "datetime_lt", label: "日期时间（小于）" },
        { value: "number", label: "数字（相等）" },
        { value: "number_ge", label: "数字（大于等于）" },
        { value: "number_le", label: "数字（小于等于）" },
        { value: "number_gt", label: "数字（大于）" },
        { value: "number_lt", label: "数字（小于）" },
        { value: "number_in", label: "数字（包含）" },
        { value: "string", label: "字符串（相等）" },
        { value: "string_like", label: "字符串（模糊）" },
        { value: "string_in", label: "字符串（包含）" },
      ],
      dataTypeMap: [
        { value: 1, label: "请求地址" },
        { value: 2, label: "自定义" },
        { value: 3, label: "sql语句" },
      ],
      buttonControlType: [
        { value: "businessButtonAdd", label: "新增" },
        { value: "businessButtonDelete", label: "删除" },
        { value: "businessButtonEdit", label: "编辑" },
        { value: "businessButtonImport", label: "导入" },
        { value: "businessButtonExport", label: "导出" },
        { value: "businessButtonViewFlow", label: "查看流程" },
        { value: "businessButtonCustom", label: "自定义" },
      ],
      flowButtonType: [
        { value: "businessButtonFlow_unreported", label: "未上报" },
        { value: "businessButtonFlow_flowing", label: "流程中" },
        { value: "businessButtonFlow_completed", label: "已完成" },
        { value: "businessButtonFlow_invalid", label: "已作废" },
      ],
      timeType: [
        { value: "yyyy-MM-dd hh:mm:ss", label: "年-月-日 时:分:秒" },
        { value: "yyyy-MM-dd hh:mm", label: "年-月-日 时:分" },
        { value: "yyyy-MM-dd", label: "年-月-日" },
        { value: "yyyy-MM", label: "年-月" },
        { value: "yyyy", label: "年" },
      ],
      pageTypeMap: [
        { value: 1, label: "电脑端" },
        { value: 2, label: "手机端" },
      ],
      templateMap: [
        { value: "1", label: "有流程模板" },
        { value: "2", label: "无流程模板" },
      ],
      contentTypeMap: [
        { value: "1", label: "键值对" },
        { value: "2", label: "JSON" },
      ],
      windowTypeMap: [
        { value: 0, label: "无" },
        { value: 1, label: "模块" },
        { value: 2, label: "弹窗" },
      ],
      tableList: [],
      pageList: [],
      selectComponents: [],
      comSelectShow: false,
      comName: null,
      checkedCom: [],
      comData: {
        params: {},
        return: {},
      },
      comDataParamsString: "",
      comDataReturnString: "",
      systemComList: [
        { id: -1, text: "选用户" },
        { id: -2, text: "选部门" },
        { id: -3, text: "选菜单" },
        { id: -4, text: "选资金科目" },
        { id: -5, text: "选物资类别" },
      ],
      methodName: "",
      headMethodName: "", //表头配置中事件内容字段名
      activeComInfo: {},
      relatedPageInfo: {},
      relatedPageShow: false,
      options: [
        {
          value: true,
          label: "是",
        },
        {
          value: false,
          label: "否",
        },
      ],
      eventTypeOptions: [
        {
          value: "0",
          label: "左键单击",
        },
        {
          value: "1",
          label: "右键单击",
        },
        {
          value: "2",
          label: "左键双击",
        },
      ],
      eventTypeValue: "0", //表头配置中事件类型选择
      showWinCom: false, //表头配置中，事件内容双击事件控制字段
      isComOrHeader: "", //当前双击事件是组件还是表头字段
      pcomeventsData: {}, //双击事件弹窗传递数据
      dataSourceOptions: [
        {
          value: "true",
          label: "系统",
        },
        {
          value: "false",
          label: "业务",
        },
      ],
      dataSourceValue: "false",
      //多数据源字段
      microId: "",
      moreDataSource: [],
      moreDataSourceValue: {},
      cellTypeOptions: [
        {
          value: "0",
          label: "文本",
        },
        {
          value: "1",
          label: "超链接",
        },
        {
          value: "2",
          label: "按钮",
        },
        {
          value: "3",
          label: "图标(文字)",
        },
      ],
      cellTypeValue: {
        value: "0",
        label: "文本",
      },
      coloumTypeValue: "",
      coloumTypeValueSend: "",
      windowTypeMapShow: false,
      systemInputDialogVisible: false,
      systemInputDialogArr: [],
      systemInputDialogType: null,
      systemInputDialogDynamicTags: [],
      systemInputDialogDynamicInputVisible: false,
      systemInputDialogDynamicInputValue: "",
      systemInputDialogDynamicCheckBox: [
        false,
        false,
        false,
        false,
        false,
        false,
      ],
      //编辑器
      curCode: "",
      cmOptions: {
        tabSize: 2,
        value: "",
        // mode: "text/javascript",
        mode: { name: "javascript", json: true },
        theme: "mdn-like", //ambiance 黑色  darcula白色  rubyblue
        readOnly: false, //是否只读
        lineNumbers: true, //是否显示行数
        lineWrapping: false,//是否应该滚动或换行以获取长行
        extraKeys: { Ctrl: "autocomplete" }, //按键配置
        lineWiseCopyCut: true,
        showCursorWhenSelecting: true,
        matchBrackets: true, //括号匹配
        line: true,
        styleActiveLine: true, // 高亮选中行
        hintOptions: {
          completeSingle: true, // 当匹配只有一项的时候是否自动补全
        },
        //spellcheck: true,//指定是否对输入启用拼写检查
      },
      isConfigPageInfoChange: false, //当前页面数据是否变化
      componnetContent: "",//组件内容
      isTableHeadAdd: false,//是否为新增表头
    };
  },
  props: {
    pageId: null,
    pageTitile: null,
  },
  components: {
    Draggable,
    DraggableItem,
    TemplatePage,
    winComSelect,
    //TODO 编辑器
    codeMirrorCom,
    codeMirrorIDE,
    funTree
  },
  directives: {
    winmove,
  },
  async mounted() {
    // 关联表列表
    // tableList().then((res) => {
    //   this.tableList = res.info;
    // });
    // 自定义页面列表
    console.log("this.pageId:::" + this.pageId);
    this.getCustomPageList();
    if (this.pageId) {
      // this.title = "编辑页面";
      this.title = this.pageTitile + "(编辑)";
      await this.pageInitialization();
    } else {
      this.title = "新增页面";
    }
    //获取数据源
    await this.getDataSource();
    //获取数据源下的表数据
    await this.getMoreDataSourceDetail();
    // 表头
    this.createTable(this.originTable);
    //页面加载完成
    this.isConfigPageInfoChange = false;
  },
  watch: {
    pageInfo: {
      handler(newV, oldV) {
        console.log("我变化了。。。。");
        this.isConfigPageInfoChange = true;
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    templateChange(e) {
      // if(!this.pageInfo.template || this.pageInfo.template=='1'){
      //     this.pageInfo.sql = `select b.WF_STATE,b.WFINST_ID, b.WF_NODE,b.wpinst_node_id,b.rep_id, b.FILL_DEPT_ID,
      //     b.FILL_DEPT_name,b.FILL_USER_ID,b.FILL_USER_name,b.FILL_DATE, a.* from ${this.pageInfo.tableName}
      //     a left join t_work b on a.${this.pageInfo.primaryName} = b.work_id @@where`;
      //   }else{
      //     this.pageInfo.sql = `select a.* from ${this.pageInfo.tableName} a @@where`;
      //   }
      if (this.pageInfo.sql) {
        switch (e) {
          case '1':
            //有流程模板
            this.pageInfo.sql = `select b.WF_STATE,b.WFINST_ID, b.WF_NODE,b.wpinst_node_id,b.rep_id, b.FILL_DEPT_ID,
            b.FILL_DEPT_name,b.FILL_USER_ID,b.FILL_USER_name,b.FILL_DATE, a.* from ${this.pageInfo.tableName}
            a left join t_work b on a.${this.pageInfo.primaryName} = b.work_id @@where`;
            break;
          case '2':
            //无流程模板
            this.pageInfo.sql = `select a.* from ${this.pageInfo.tableName} a @@where`;
            break;
        }
      }
    },
    codeFormatte() {
      /*
       *@description:编辑器代码格式化
       *@author: xuzhaoqian
       *@date: 2021-06-17 10:53:41
       *@version: V1.0.5
      */
      this.$refs.codeMirrorIDERef.codeFormat();
    },
    checkBoxChange(index, e) {
      //TODO 复选框改变事件
      console.log(e);
      if (index <= this.systemInputDialogDynamicCheckBox.length - 1) {
        this.$set(this.systemInputDialogDynamicCheckBox, index, e);
      } else {
        this.systemInputDialogDynamicCheckBox.push(e);
      }
      switch (index) {
        case 0:
          //请求地址
          console.log(e);
          if (e) {
            this.curCode += "url:" + this.activeData.url;
          } else {
            // console.log(typeof this.curCode)
            // var reg=new RegExp(this.activeData.url,"g");
            // this.curCode.replace(reg,"");
          }
          break;
        case 1:
          //请求参数
          this.curCode += "\n" + "data:" + this.activeData.params;
          break;
        case 2:
          //参数值
          this.curCode = "";
          break;
        case 3:
          //窗体类型
          this.curCode = "let type=1;\n" + this.curCode;
          break;
        case 4:
          //关联窗体
          this.handleComSelect("comConfig", null);
          break;
        case 5:
          //是否多选
          break;
      }
      console.log("curCode:::" + this.curCode);
      console.log(
        "systemInputDialogDynamicCheckBox:::::" +
        JSON.stringify(this.systemInputDialogDynamicCheckBox)
      );
    },
    systemInputDialogDynamicHandleClose(tag) {
      this.systemInputDialogDynamicTags.splice(
        this.systemInputDialogDynamicTags.indexOf(tag),
        1
      );
    },

    systemInputDialogDynamicShowInput() {
      this.systemInputDialogDynamicInputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    systemInputDialogDynamicHandleInputConfirm() {
      let systemInputDialogDynamicInputValue = this
        .systemInputDialogDynamicInputValue;
      if (systemInputDialogDynamicInputValue) {
        this.systemInputDialogDynamicTags.push(
          systemInputDialogDynamicInputValue
        );
      }
      this.systemInputDialogDynamicInputVisible = false;
      this.systemInputDialogDynamicInputValue = "";
    },
    systemInputDialogFun(index) {
      /**
       * 参数值弹出框确定和取消事件
       * 判断当前是请求参数还是请求值
       */
      console.log(this.systemInputDialogType);
      this.curCode = this.$refs.codeMirrorIDERef.editorValue;
      if (index) {
        switch (this.systemInputDialogType) {
          case "params":
            //请求参数
            if (index) {
              //确定按钮
              this.activeData.params =
                // "cellParams":' +
                "{" + JSON.stringify(this.systemInputDialogDynamicTags) + "}";
            } else {
              console.log("this.pageInfo:::" + JSON.stringify(this.pageInfo));
              //取消按钮
              this.systemInputDialogDynamicTags = [];
              this.curCode = "";
            }
            break;
          case "paramsValue":
            //参数值
            let paramsValueObj = {};
            this.systemInputDialogArr.forEach((item) => {
              paramsValueObj[item.key] = item.value;
            });
            if (index) {
              this.activeData.paramsValue = JSON.stringify(paramsValueObj);
            } else {
              this.activeData.paramsValue = "";
            }
            break;
          case "scriptStatements":
            //脚本
            this.activeData.sql = this.curCode;
            break;
          case "tableScript":
            //表头脚本
            this.$set(this.tableCellInfo, "sql", this.curCode);
            break;
          case "initScript":
            this.$set(this.pageInfo, "initJs", this.curCode);
            break;
        }
      } else {
        this.curCode = "";
      }
      this.systemInputDialogVisible = false;
    },
    systemInputFocus(param) {
      //参数值输入框获取焦点事件
      this.systemInputDialogVisible = true;
      this.systemInputDialogArr = [];
      this.systemInputDialogDynamicTags = [];
      this.systemInputDialogType = param;
      switch (param) {
        case "params":
          let systemInputVal = JSON.parse(this.activeData.params).cellParams;
          systemInputVal.forEach((item) => {
            this.systemInputDialogDynamicTags.push(item);
          });
          break;
        case "paramsValue":
          if (!this.activeData.paramsValue) {
            let systemInputVal = JSON.parse(this.activeData.params).cellParams;
            systemInputVal.forEach((item) => {
              console.log("item" + item);
              let obj = {};
              obj.key = item;
              obj.value = "";
              this.systemInputDialogArr.push(obj);
            });
          } else {
            for (let item in JSON.parse(this.activeData.paramsValue)) {
              let obj = {};
              obj.key = item;
              obj.value = JSON.parse(this.activeData.paramsValue)[item];
              this.systemInputDialogArr.push(obj);
            }
          }
          break;
        case "scriptStatements":
          this.curCode = "";
          this.curCode = this.activeData.sql;
          this.$nextTick(() => {
            this.$refs.codeMirrorIDERef.editorValue = this.curCode;
          })

          break;
        case "tableScript":
          //表头脚本
          if (this.tableCellInfo.hasOwnProperty("sql")) {
            this.curCode = this.tableCellInfo.sql;
            this.$nextTick(() => {
              this.$refs.codeMirrorIDERef.editorValue = this.curCode;
            })

          }
          break;
        case "initScript":
          this.curCode = this.pageInfo.initJs;
          this.$nextTick(() => {
            this.$refs.codeMirrorIDERef.editorValue = this.curCode;
          })
          break;
      }
    },
    windowTypeMapChange(value) {
      //TODO 组件配置窗体类型下拉框改变事件
      console.log(value);
      if (value == 0) {
        this.windowTypeMapShow = false;
        this.activeData.method = null;
      } else {
        this.windowTypeMapShow = true;
      }
    },
    async pageInitialization() {
      const detail = await pageDetail({ id: this.pageId });
      this.pageInfo = detail.info;
      this.microId = detail.info.microId;
      // 关联表
      this.tableInfo = {
        id: detail.info.tableId,
        name: detail.info.tableName,
      };
      const children = detail.info.control.children;
      //TODO  修改  增加drawingList的长度，+1
      for (let i = 0; i < 2; i++) {
        this.drawingList[i].id = children[i].id;
        if (!children[i].children) {
          this.drawingList[i].children = [];
        } else {
          const child = children[i].children;
          child.forEach((element) => {
            element.formId = ++this.idGlobal;
            element.vModel = `field${this.idGlobal}`;
            element.clearable = Boolean(element.clearable);
            element.id = String(element.id);
          });
          this.drawingList[i].children = child;
        }
      }
      this.activeData = this.drawingList[0];
      this.activeId = this.drawingList[0].formId;
      this.originTable = JSON.parse(this.pageInfo.control.children[2].extattr);
      this.tableHeaderInfo = children[2];
    },
    createTable(data) {
      console.log("表头数据属性：" + JSON.stringify(data));
      const colLength = data.cols ? data.cols + 2 : 10;
      const rowLength = data.rows ? Object.keys(data.rows).length + 1 : 4;
      const s = new Spreadsheet("#x-spreadsheet", {
        view: {
          height: () => 300,
        },
        row: {
          len: rowLength,
          height: 25,
        },
        col: {
          len: colLength,
        },
      })
        .change((data) => {
          console.log("change:" + JSON.stringify(data));
          this.originTable = {
            cols: data.cols.len,
            rows: data.rows,
          };
        })
        .on("cell-selected", (cell) => {
          console.log("单元格点击");
          console.log(JSON.stringify(cell));
          if (cell) {
            this.tableCellInfo = cell;
            cell = this.tableCellInfo;
            this.isTableHeadAdd = false;
            // TODO  新增 表头配置信息
            //this.headActivData=this.tableCellInfo;
            //判断当前表头是否存在信息
            switch (cell.coloumTypeValue) {
              case "0":
                this.coloumTypeValue = 0;
                this.cellTypeValue = {
                  value: "0",
                  label: "文本",
                };
                break;
              case "1":
                this.coloumTypeValue = 1;
                this.cellTypeValue = {
                  value: "1",
                  label: "超链接",
                };
                break;
              case "2":
                this.coloumTypeValue = 2;
                this.cellTypeValue = {
                  value: "2",
                  label: "按钮",
                };
                break;
              case "3":
                this.coloumTypeValue = 3;
                this.cellTypeValue = {
                  value: "3",
                  label: "图标(文本)",
                };
                break;
              default:
                this.coloumTypeValue = 0;
                this.cellTypeValue = {
                  value: "0",
                  label: "文本",
                };
                break;
            }
          } else {
            this.tableCellInfo = {};
            this.isTableHeadAdd = true;
          }
          this.activeTab = "tableCellInfo";
        });
      s.loadData(data);
      s.validate();
    },
    // 控件创建
    cloneComponent(origin) {
      const clone = JSON.parse(JSON.stringify(origin));
      clone.formId = ++this.idGlobal;
      clone.renderKey = +new Date(); // 改变renderKey后可以实现强制更新组件
      clone.code = clone.code + "_" + this.idGlobal;
      if (!clone.layout) clone.layout = "colFormItem";
      if (clone.layout === "colFormItem") {
        clone.vModel = `field${this.idGlobal}`;
        clone.placeholder !== undefined;
        tempActiveData = clone;
      } else if (clone.layout === "rowFormItem") {
        delete clone.label;
        clone.componentName = `row${this.idGlobal}`;
        clone.gutter = this.formConf.gutter;
        tempActiveData = clone;
      }
      return tempActiveData;
    },
    // 控件复制
    drawingItemCopy(item, parent) {
      let clone = JSON.parse(JSON.stringify(item));
      clone = this.createIdAndKey(clone);
      parent.push(clone);
    },
    createIdAndKey(item) {
      item.formId = ++this.idGlobal;
      item.renderKey = +new Date();
      delete item.id;
      if (item.layout === "colFormItem") {
        item.vModel = `field${this.idGlobal}`;
      } else if (item.layout === "rowFormItem") {
        item.componentName = `row${this.idGlobal}`;
      }
      if (Array.isArray(item.children)) {
        item.children = item.children.map((childItem) =>
          this.createIdAndKey(childItem)
        );
      }
      return item;
    },
    // 控件删除
    drawingItemDelete(index, parent) {
      parent.splice(index, 1);
    },
    // 控件点击
    activeFormItem(element) {
      console.log("控件点击：" + JSON.stringify(element));
      //TODO  新增、删除、修改等按钮手动给对象增加请求地址
      switch (element.attr) {
        case "businessButtonAdd":
          //新增
          if (!element.sql) {
            element.sql = `
              let url="/dept/selectFillDept";
              let data = {funcId:"",funcCode:"",type:2};
              sys.Add(url,data);
            `;
          }
          break;
        case "businessButtonDelete":
          //删除
          if (!element.sql) {
            element.sql = `
             let url="/page/remove";
            let data ={pageId:null,values:[""],menuId:null,menuCode:null};
            sys.Delete(url,data);
            `;
          }
          break;
        case "businessButtonEdit":
          //编辑
          if (!element.sql) {
            element.sql = `
             let url="/role/editAut2";
            let data ={funcId:null,funcCode:null,tableName:"",id:"",keyName:""};
            sys.Edit(url,data);
            `;
          }
          break;
        case "businessButtonViewFlow":
          //查看流程
          if (!element.url) {
            element.url = "";
          }
          if (!element.sql) {
            element.sql = `
             let id="";
            sys.ViewFlow(id);
            `;
          }
          break;
        case "businessButtonExport":
          //导出
          if (!element.sql) {
            element.sql = `
             let url="/page/export";
            let data ={pageId:null,values:[""],menuId:null,menuCode:null};
            sys.Delete(url,data);
            `;
          }
          break;
        case "businessButtonImport":
          //导入
          if (!element.sql) {
            element.sql = `
             let url="/dept/selectFillDept";
            let data = {funcId:null,funcCode:"",type:2};
            sys.Add(url,data);
            `;
          }
          break;
      }
      if (!element.componentName) {
        this.activeTab = "componentInfo";
        this.activeData = element;
        if (this.activeData.executeDb == null) {
          this.activeData.executeDb = this.dataSourceValue;
        }
        this.activeId = element.formId;
        if (element.dataType === 1 && typeof element.data === "string") {
          element.data = JSON.parse(element.data);
        }
      }
      if (element.formType != null && element.formType > 0) {
        this.windowTypeMapShow = true;
      } else {
        element.formType = 0;
        this.windowTypeMapShow = false;
      }
      if (element.method) {
        // 检索区为双击事件，按钮区为单击事件
        // this.methodName = this.getComInfo(JSON.parse(element.method)).text
        //this.methodName =  element.method.dblcomText;
        // this.methodName = JSON.parse(element.method).dblcomText;
        // if (this.methodName) { // 检索组件【双击事件】已配置
        //         this.checkedCom = []
        //         this.checkedCom.push(JSON.parse(this.activeData.method))
        //         const paramsObj = JSON.parse(this.activeData.params);
        //         this.comDataReturnString = Object.keys(paramsObj.return).length > 0 ? JSON.stringify(paramsObj.return) : ''
        //         this.comDataParamsString = Object.keys(paramsObj.params).length > 0 ? JSON.stringify(paramsObj.params) : ''
        //         this.activeComInfo = this.getComInfo(JSON.parse(this.activeData.method))
        //       }
        // this.comSelectShow = true;
      } else {
        this.methodName = "";
      }
    },
    onEnd(obj) {
      if (obj.from !== obj.to) {
        this.activeData = tempActiveData;
        if (this.activeData.type === "flowButton") {
          this.activeData.url = "/page/count?controlId=@@controlId";
        }
        this.activeId = this.idGlobal;
      }
    },
    selectChange(e) {
      if (e === 1) {
        this.activeData.data = {
          key: null,
          value: null,
        };
      } else if (e === 2) {
        this.activeData.data = `[{"value":1,"label":"电脑端"},{"value":2,"label":"手机端"}]`;
        this.activeData.url = null;
      } else if (e === 3) {
        this.activeData.data = `[{"value":"ID"},{"label":"NAME"}]`;
        this.activeData.sql = null;
        this.activeData.url = "/page/dropDown?controlId=@@controlId";
      }
    },
    // 全屏
    handleFullScreen() {
      this.fullScreen = !this.fullScreen;
    },
    // 预览
    async perview() {
      await this.createContent();
      this.dialogFormVisible = true;
    },
    // 关闭
    cancel() {
      /*
       *@description:如果当前页面内容发生变化，则给用户提示，否则不提示
       *@modifyContent:
       *@author: xuzhaoqian
       *@date: 2021-05-31 10:12:42
       */
      if (this.isConfigPageInfoChange) {
        this.messageBox(
          "是否在离开页面前保存修改？",
          "提示",
          "不保存",
          "保存"
        ).then((c) => {
          if (c.type === "confirm") {
            this.$emit("configPageClose", "close");
            this.isConfigPageInfoChange = false;
          } else if (c.type === "cancel") {
            this.$emit("configPageClose", "close");
            this.save();
            this.$emit("configPageClose", "close");
          }
        });
      } else {
        this.$emit("configPageClose", "close");
        this.isConfigPageInfoChange = false;
      }
    },
    // 保存
    async save() {
      const pageInfo = await this.createContent();
      console.log("pageInfo123:", pageInfo);
      pageInfo.microId = this.microId;
      if (pageInfo) {
        pageSave(pageInfo).then((res) => {
          if (res.success) {
            console.log("保存成功....");
            this.pageInfo = res.info;
            this.tableHeaderInfo = res.info.control.children[2];
            this.message(res.msg, 1);
            //TODO 新增
            this.isConfigPageInfoChange = false;
          } else {
            console.log("保存失败....");
            console.log(JSON.stringify(res));
            if (res.code === "199") {
              this.message(res.info, 3);
              return false;
            } else if (res.code === "100") {
              this.message(res.msg, 3);
              return false;
            }
          }
        });
      }
    },
    async createContent() {
      console.log("pageInfo:" + JSON.stringify(this.pageInfo));
      let array = JSON.parse(JSON.stringify(this.pageInfo));
      if (!array.text) {
        this.message("请输入页面名称", 3);
        this.activeTab = "pageInfo";
        return;
      }
      if (!array.code) {
        this.message("请输入页面编码", 3);
        this.activeTab = "pageInfo";
        return;
      }
      if (!array.type) {
        this.message("请选择应用类型", 3);
        this.activeTab = "pageInfo";
        return;
      }
      if (!array.tableName) {
        this.message("请选择关联表", 3);
        this.activeTab = "pageInfo";
        return;
      }
      // 新增
      if (!array.id) {
        array.control = {
          label: array.text + "_control",
          code: array.text + "_control_code",
          type: "div",
        };
        this.drawingList.forEach((item) => {
          delete item.id;
        });
      }
      // console.log("drawingList:"+JSON.stringify(this.drawingList))
      array.control.children = JSON.parse(JSON.stringify(this.drawingList));
      // 组件验证
      console.log("组件验证......");
      const component = array.control.children;
      this.componentValidation(component);
      // 表头
      const tableHead = await this.tableHeadInitialization(array);
      array.control.children.push(tableHead);
      return array;
    },
    componentValidation(component) {
      for (let i in component) {
        if (component[i].children.length > 0) {
          const control = component[i].children;
          for (let key in control) {
            if (component[i].code === "search") {
              if (!control[key].extattr) {
                this.message(`请选择控件【${control[key].label}】类型`, 3);
                return;
              }
              if (!control[key].attr) {
                this.message(`请输入控件【${control[key].label}】查询字段`, 3);
                return;
              }
              if (control[key].dataType === 1) {
                control[key].data = JSON.stringify(control[key].data);
              }
            } else {
              control[key].rowNum = Number(control[key].rowNum);
              if (!control[key].attr) {
                this.message(
                  `请选择按钮【${control[key].defaultValue}】类型`,
                  3
                );
                return;
              }
            }
          }
        }
      }
    },
    tableHeadInitialization(array) {
      if (this.isTableHeadAdd) {
        //新增表头
        let cells = this.originTable.rows[0].cells;
        let cellKeyArr = Object.keys(cells);
        Object.defineProperty(cells, cellKeyArr.length, this.tableCellInfo);
        this.isTableHeadAdd = false;
      }
      //TODO 把表头配置属性赋值给pageInfo,进行整体的数据保存整理
      let data = {};
      if (!array.id) {
        //TODO 表头数据为空
        data = {
          label: "table",
          code: "table_code",
          type: "table",
        };
      } else {
        //TODO 表头数据不为空
        data = JSON.parse(JSON.stringify(this.tableHeaderInfo));
      }
      if (this.originTable && this.originTable.length !== 0) {
        // TODO 表头配置信息不为空
        data.extattr = JSON.stringify(this.originTable);
      }
      return data;
    },
    // 预览
    handlePerviewPage(e) {
      console.log('关闭........')
      console.log(e)
      if (e === "close") {
        this.dialogFormVisible = false;
      }
    },
    // 关联表
    async tableChange(e) {
      const columns = await columnList({ tid: e.id });
      let columnNames = "";
      let primaryName = "";
      for (let i = 0; i < columns.info.length; i++) {
        if (columns.info[i].primary) {
          primaryName = columns.info[i].name;
        }
        columnNames += "a." + columns.info[i].name + ",";
      }
      if (!primaryName) {
        this.message("关联表没有主键，请重新选择", 3);
        this.tableInfo = {};
        this.pageInfo.primaryName = "";
        this.pageInfo.sql = "";
        return;
      } else {
        columnNames = columnNames.substring(0, columnNames.length - 1);
        this.pageInfo.tableName = e.name;
        this.pageInfo.tableId = e.id;
        this.pageInfo.primaryName = primaryName;
        if (!this.pageInfo.template || this.pageInfo.template == '1') {
          this.pageInfo.sql = `select b.WF_STATE,b.WFINST_ID, b.WF_NODE,b.wpinst_node_id,b.rep_id, b.FILL_DEPT_ID,
            b.FILL_DEPT_name,b.FILL_USER_ID,b.FILL_USER_name,b.FILL_DATE, a.* from ${this.pageInfo.tableName}
            a left join t_work b on a.${this.pageInfo.primaryName} = b.work_id @@where`;
        } else {
          this.pageInfo.sql = `select a.* from ${this.pageInfo.tableName} a @@where`;
        }

      }
    },
    buttonChange(e) {
      console.log("按钮类型：：：" + JSON.stringify(e));
      switch (e) {
        case "businessButtonAdd":
          this.activeData.defaultValue = "新增";
          //TODO 新增脚本
          this.activeData.code = "button_Add";
          this.activeData.sql = `
              let url="/dept/selectFillDept";
            let data = {funcId:null,funcCode:"",type:2};
            sys.Add(url,data);
            `;
          break;
        case "businessButtonDelete":
          this.activeData.defaultValue = "删除";
          this.activeData.code = "button_Delete";
          this.activeData.sql = `
            let url="/page/remove";
            let data ={pageId:null,values:[""],menuId:null,menuCode:null};
            sys.Delete(url,data);
            `;
          // if(!this.activeData.sql){
          // }
          break;
        case "businessButtonEdit":
          this.activeData.defaultValue = "编辑";
          this.activeData.code = "button_Edite";
          this.activeData.sql = `
            let url="/role/editAut2";
            let data ={funcId:null,funcCode:null,tableName:"",id:"",keyName:""};
            sys.Edit(url,data);
            `;
          break;
        case "businessButtonImport":
          this.activeData.defaultValue = "导入";
          this.activeData.code = "button_Import";
          this.activeData.sql = `
            let url="/dept/selectFillDept";
            let data = {funcId:null,funcCode:"",type:2};
            sys.Import(url,data);
            `;
          break;
        case "businessButtonExport":
          this.activeData.defaultValue = "导出";
          this.activeData.code = "button_Export";
          this.activeData.sql = `
            let url="/page/export";
            let data ={pageId:null,values:[""],menuId:null,menuCode:null};
            sys.Export(url,data);
            `;
          break;
        case "businessButtonViewFlow":
          this.activeData.defaultValue = "查看流程";
          this.activeData.code = "button_ViewFlow";
          this.activeData.sql = `
            let id="";
            sys.ViewFlow(id);
            `;
          break;
        case "businessButtonCustom":
          this.activeData.defaultValue = "自定义";
          this.activeData.code = "button_Custom";
          this.activeData.sql = ``;
          break;
      }
      this.curCode = this.activeData.sql;
    },
    flowButtonChange(e) {
      switch (e) {
        case "businessButtonFlow_unreported":
          this.activeData.defaultValue = "未上报";
          this.activeData.sql = `select count(*) from ${this.pageInfo.tableName} t
          LEFT JOIN T_WORK z ON z.WORK_ID = t.${this.pageInfo.primaryName} @@where z.wf_state = 0`;
          break;
        case "businessButtonFlow_flowing":
          this.activeData.defaultValue = "流程中";
          this.activeData.sql = `select count(*) from ${this.pageInfo.tableName} t
          LEFT JOIN T_WORK z ON z.WORK_ID = t.${this.pageInfo.primaryName} @@where z.wf_state = 1`;
          break;
        case "businessButtonFlow_completed":
          this.activeData.defaultValue = "已完成";
          this.activeData.sql = `select count(*) from ${this.pageInfo.tableName} t
          LEFT JOIN T_WORK z ON z.WORK_ID = t.${this.pageInfo.primaryName} @@where z.wf_state = 2`;
          break;
        default:
          this.activeData.sql = `select count(*) from ${this.pageInfo.tableName} t
          LEFT JOIN T_WORK z ON z.WORK_ID = t.${this.pageInfo.primaryName} @@where z.wf_state = -1`;
          this.activeData.defaultValue = "已作废";
      }
    },
    handleReferChange(e) {
      if (e) {
        let map = [];
        const children = this.drawingList[0].children;
        children.forEach((item) => {
          if (item.code !== this.activeData.code) {
            map.push(item);
          }
        });
        this.selectComponents = map;
      }
    },
    handleComSelect(eventTypeValue, tableInfo) {
      //TODO eventTypeValue :comConfig组件配置中的双击事件  headConfig：表头配置中的事件内容双击
      this.isComOrHeader = eventTypeValue;
      console.log("eventTypeValue" + JSON.stringify(eventTypeValue));
      switch (eventTypeValue) {
        case "comConfig":
          //TODO 组件配置中的双击事件
          if (this.methodName) {
            // 检索组件【双击事件】已配置
            // this.checkedCom = []
            // this.checkedCom.push(JSON.parse(this.activeData.method))
            // const paramsObj = JSON.parse(this.activeData.params);
            console.log(this.activeData.method);
            this.pcomeventsData = this.activeData.method;
            // this.comDataReturnString = Object.keys(paramsObj.return).length > 0 ? JSON.stringify(paramsObj.return) : ''
            // this.comDataParamsString = Object.keys(paramsObj.params).length > 0 ? JSON.stringify(paramsObj.params) : ''
            // this.activeComInfo = this.getComInfo(JSON.parse(this.activeData.method))
          }
          break;
        case "headConfig":
          //tableInfo:::   {"text":"计划名称","prop":"MONTH_PLAN_NAME","width":"120"}
          //TODO 表头配置中的事件内容双击
          //当前表头是否配置事件内容，如果没配置，传的值为空，配置后显示配置的值
          console.log("tableInfo:" + JSON.stringify(tableInfo));
          if (
            tableInfo.hasOwnProperty("eventContentHeader") &&
            tableInfo != "icon"
          ) {
            //含有事件内容
            //this.pcomeventsData=tableInfo;
            this.coloumTypeValueSend = "";
          } else if (tableInfo == "icon") {
            this.coloumTypeValueSend = this.coloumTypeValue;
          } else {
            this.pcomeventsData = "";
            this.coloumTypeValueSend = "";
          }
          // if (this.headMethodName) {
          //   console.log(this.headActivData.method);
          //   this.pcomeventsData = this.headActivData.method;
          // }
          break;
      }
      // this.comSelectShow = true;
      this.relatedPageShow = true;
    },
    async handleComCheck(e) {
      if (e.length > 1) {
        // 单选
        e.splice(0, 1);
      }
      this.activeComInfo = await this.getComInfo(e[0]);
      if (this.activeData.type !== "button") {
        // 检索组件双击事件
        this.formateSeachDbEvent(e);
      }
    },
    formateSeachDbEvent(e) {
      // 取消勾选
      if (!e.length) {
        this.comDataReturnString = "";
        this.comDataParamsString = "";
        return;
      }
      this.comData.return[this.activeData.code] = "params";
      if (e[0] < 0) {
        // 系统组件
        this.systemComInitialization(e);
      } else {
        // 自定义组件
        this.comData.params = {
          id: this.activeComInfo.id,
          menuCode: this.activeComInfo.code,
          multipleChoice: "1",
          dialogTitle: this.activeComInfo.text,
        };
      }
      this.comDataParamsString =
        Object.keys(this.comData.params).length > 0
          ? JSON.stringify(this.comData.params)
          : "";
      this.comDataReturnString = JSON.stringify(this.comData.return);
    },
    systemComInitialization(e) {
      switch (Number(e[0])) {
        case -1: // 选人员
          this.comData.params = {
            userFlag: true,
            parentId: 0,
          };
          break;
        case -2: // 选部门
          this.comData.params = {
            userFlag: false,
            parentId: 0,
          };
          break;
        case -5:
          this.comData.params = {
            type: 3,
            title: "物资类别选择",
            checkBox: 2,
            params: { LX: 2 },
            param: { parentId: 0 },
          };
          break;
        default:
          // 菜单&资金科目
          this.comData.params = {};
      }
    },
    getComInfo(id) {
      let comInfo = {};
      if (id < 0) {
        // 系统组件
        for (let i = 0; i < this.systemComList.length; i++) {
          if (this.systemComList[i].id === id) {
            comInfo = this.systemComList[i];
          }
        }
      } else {
        for (let i = 0; i < this.pageList.length; i++) {
          if (this.pageList[i].id === id) {
            comInfo = this.pageList[i];
          }
        }
      }
      return comInfo;
    },
    // 双击事件保存
    comSelectConfirm() {
      this.comData.return = this.comDataReturnString
        ? JSON.parse(this.comDataReturnString)
        : null;
      this.comData.params = this.comDataParamsString
        ? JSON.parse(this.comDataParamsString)
        : null;
      this.activeData.params = JSON.stringify(this.comData);
      this.activeData.method = this.activeComInfo.id;
      this.methodName = this.activeComInfo.text;
      this.comSelectShow = false;
    },
    // 按钮组件 关联窗体
    handleRelatedPage() {
      let info = {
        name: "",
        route: "",
        multipleChoice: true,
      };
      if (this.activeData.method) {
        info = JSON.parse(this.activeData.method);
      }
      this.relatedPageInfo = info;
      this.relatedPageShow = true;
    },
    relatedPageSave() {
      this.activeData.method = JSON.stringify(this.relatedPageInfo);
      this.methodName = this.relatedPageInfo.name;
      this.relatedPageShow = false;
    },
    getCustomPageList() {
      pageQuery({
        customPage: {
          type: 1,
          text: this.comName,
        },
        pageSize: 0,
        pageIndex: 0,
      }).then((res) => {
        this.pageList = res.info;
      });
    },
    closeWinCom() {
      this.relatedPageShow = false;
    },
    insertCodemirror(val) {
      let pos1 = this.$refs.mycode.codemirror.getCursor();
      let pos2 = {};
      pos2.line = pos1.line;
      pos2.ch = pos1.ch;
      this.$refs.mycode.codemirror.replaceRange(val, pos2);
    },
    saveWinCom(info) {
      console.log("info:" + JSON.stringify(info));
      // this.methodName = info.dblcomText;
      this.componnetContent = JSON.stringify(info);
      this.relatedPageShow = false;
      // this.insertCodemirror(this.componnetContent);
      let selectInfo = `
          let data=${this.componnetContent};
          sys.openComponent(data);
        `
      this.$refs.codeMirrorIDERef.insertCodemirror(selectInfo);
      this.codeFormatte();//自动格式化
      return;
      //TODO 判断当前双击事件是组件还是表头，进行对应的数据渲染
      switch (this.isComOrHeader) {
        case "comConfig":
          //组件配置
          this.activeData.method = JSON.stringify(info);
          this.methodName = info.dblcomText;
          this.relatedPageShow = false;
          break;
        case "headConfig":
          if (info.hasOwnProperty("font_class")) {
            this.$set(this.tableCellInfo, "iconClass", info.font_class);
            this.relatedPageShow = false;
            return;
          }
          //表头配置
          this.headActivData.method = info;
          this.headMethodName = info.dblcomText;
          info.mouseEvenType = this.eventTypeValue;
          info.prop = this.tableCellInfo.prop;
          info.coloumTypeValue = this.coloumTypeValue;
          this.$set(
            this.tableCellInfo,
            "eventContentHeader",
            this.headMethodName
          );
          this.$set(
            this.tableCellInfo,
            "coloumTypeValue",
            this.coloumTypeValue
          );
          //把组件信息对象和tableCellInfo对象合并
          Object.assign(this.tableCellInfo, info);

          if (this.tableCellInfo.hasOwnProperty("iconClass")) {
            info.iconClass = this.tableCellInfo.iconClass;
          }
          // if (this.tableHeaderInfo.children) {
          //   //TODO 判断当前数组内是否含有该条数据,含有则删除
          //   for (let i = 0; i < this.tableHeaderInfo.children; i++) {
          //     if (this.tableHeaderInfo.children[i].prop == info.prop) {
          //       this.tableHeaderInfo.children.splice(i, 1);
          //     }
          //   }
          //   this.tableHeaderInfo.children.push(info);
          // } else {
          //   this.tableHeaderInfo.children = [];
          //   this.tableHeaderInfo.children.push(info);
          // }
          this.relatedPageShow = false;
          break;
      }
    },
    getMoreDataSourceDetail() {
      //获取数据源下的详情
      let dataObj = {};
      dataObj.pid = 0;
      dataObj.parentId = 0;
      dataObj.pid = 0;
      dataObj.microId = this.microId;
      getTableListByDataSourcId(dataObj).then((res) => {
        this.tableList = [];
        if (res.info.length > 0) {
          res.info.forEach((item) => {
            this.tableList.push(item);
          });
          if (this.microId != this.pageInfo.microId) {
            this.tableInfo = {};
            this.$set(this.pageInfo, "primaryName", "");
            this.$set(this.pageInfo, "sql", "");
          }
        } else {
          this.tableInfo = {};
          this.$set(this.pageInfo, "primaryName", "");
          this.$set(this.pageInfo, "sql", "");
        }
      });
    },
    getDataSource() {
      getMoreDataSource().then((res) => {
        console.log(res)
        this.moreDataSource = [];
        res.info.forEach((item) => {
          if (item.id) {
            this.moreDataSource.push(item);
          }
        });
        console.log("microId::", this.microId)
        //下拉框默认显示当前数据源
        this.moreDataSource.forEach((item) => {
          console.log(item.id, this.microId);
          if (item.id == this.microId) {
            this.moreDataSourceValue = item.name;
          }
        });
      });
    },
    dataSorceChange(item) {
      //数据源改变事件
      console.log(item);
      this.microId = item;
      this.getMoreDataSourceDetail();
    },
    columSelectChange(e) {
      //表头配置中字段类型下拉框事件
      this.coloumTypeValue = e.value;
      this.tableCellInfo.coloumTypeValue = this.coloumTypeValue;
    },
    writeScp(text) {
      if (text) {
        this.$refs.codeMirrorIDERef.insertCodemirror(text);
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.templePage-wrapper {
  z-index: 9;
  width: 100%;
  height: 100%;
  background: var(--customPage-bgc);
  box-shadow: var(--customPage-boxshoadow);
  border-radius: 6px;
  position: relative;

  .title-wrapper {
    line-height: 40px;
    height: 40px;
    padding: 0 20px;
    margin: 4px;
    margin-bottom: 0;
    background: var(--customPage-title-bgc);
    display: inline-flex;
    justify-content: space-between;
    width: calc(100% - 8px);
    color: var(--customPage-title-color);

    .title {
      font-size: 18px;
      font-weight: 400;
    }

    .buttons-wrapper span {
      margin-left: 20px;
      color: var(--customPage-title-color);
      cursor: pointer;
    }
  }

  .configPageContent-wrapper {
    height: calc(100% - 44px);
    padding: 12px 0;

    .components-wrapper {
      border: 1px solid var(--customPage-content-border-color);
      overflow: auto;
      border-radius: 6px;
      margin-left: 12px;
      float: left;
      width: 234px;
      height: 100%;
      padding: 15px;
      display: flex;
      flex-direction: column;

      .row {
        text-align: left;

        span {
          display: inline-block;
          padding-left: 9px;
          font-size: 16px;
          font-weight: bold;
          color: var(--customPage-content-title-color);
          position: relative;
          margin-bottom: 22px;

          &::before {
            position: absolute;
            display: block;
            content: "";
            width: 4px;
            height: 20px;
            background: var(--customPage-content-title-icon-color);
            border-radius: 2px;
            top: 0;
            left: 0;
            transform: translateX(-100%);
          }
        }

        .components-draggable>.components-item {
          height: 40px;
          line-height: 40px;
          background: var(--customPage-left-component-bgc);
          border-radius: 6px;
          margin-bottom: 16px;
          font-size: 16px;
          color: var(--customPage-left-component-text-color);
          padding-left: 16px;
          cursor: move;

          &.sortable-chosen,
          &:hover {
            background: rgba(83, 168, 255, 1);
            opacity: 0.9;
            color: rgba(255, 255, 255, 1);
          }
        }
      }
    }

    .board-wrapper {
      border: 1px solid var(--customPage-content-border-color);
      overflow: auto;
      border-radius: 6px;
      float: left;
      height: 100%;
      margin-left: 12px;
      width: calc(100% - 628px);
      padding: 12px 15px;

      .el-form {
        .pageTitle {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 14px 20px;
          padding-bottom: 24px;

          .el-form-item {
            display: inline-block;
            width: 100%;
            margin-bottom: 0;
          }

          .buttons-wrapper {
            display: inline-flex;

            .btnAdd {
              width: 68px;
              height: 28px;
              border: 1px solid rgba(81, 167, 254, 1);
              display: inline-block;
              margin-left: 20px;
            }
          }
        }
      }

      #x-spreadsheet {
        border-radius: 6px;
        border: 1px dashed #ccc;
        padding: 20px 0;
        position: relative;
        overflow: hidden;

        &::before {
          position: absolute;
          content: "自定义表头";
          display: block;
          top: 0;
          left: 5px;
          font-size: 12px;
          color: #bbb;
        }

        ::v-deep.x-spreadsheet {
          width: 100%;
          overflow: auto;

          .x-spreadsheet-toolbar .x-spreadsheet-toolbar-btns {

            .x-spreadsheet-toolbar-btn,
            .x-spreadsheet-toolbar-divider {
              display: none;

              &:nth-child(20) {
                display: block;
              }
            }
          }

          .x-spreadsheet-bottombar {
            display: none;
          }
        }
      }
    }

    .componentsProperty-wrapper {
      margin: 0 12px;
      border-radius: 6px;
      border: 1px solid var(--customPage-content-border-color);
      overflow: hidden;
      float: left;
      height: 100%;
      width: 346px;

      .el-tabs {
        height: 100%;

        ::v-deep.el-tabs__header {
          padding: 0 24px;
          margin-bottom: 0;

          .el-tabs__item {
            font-size: 14px;
            font-family: Microsoft YaHei;
            font-weight: bold;
            color: rgba(153, 153, 153, 1);

            &.is-active {
              color: rgba(81, 167, 254, 1);
            }
          }
        }

        ::v-deep.el-tabs__content {
          overflow: auto;
          height: calc(100% - 40px);

          .el-form {
            padding: 20px;
            padding-top: 12px;

            .el-form-item {
              height: 32px;
              line-height: 32px;

              .el-form-item__label {
                height: 32px;
                line-height: 32px;
              }

              .el-form-item__content {
                height: 32px;
                line-height: 32px;
                text-align: left;

                .el-input,
                .el-select {
                  width: 100%;
                  height: 32px;
                  line-height: 32px;

                  input {
                    height: 32px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  &.fullScreen {
    z-index: 999;
    position: fixed !important;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 1);
  }

  .perviewPage-wrapper {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 999;
    background-color: #fff;
  }

  .comSelect-wrapper .systemDialog .dialog-body {
    .components-wrapper {
      height: calc(100% - 88px);

      .el-tabs {
        height: 100%;

        ::v-deep.el-tabs__content {
          height: calc(100% - 55px);

          .el-tab-pane {
            height: 100%;

            .el-checkbox-group {
              border-radius: 4px;
              overflow: auto;
              padding-left: 12px;
              padding-top: 12px;
              border: 1px solid var(--system-form-input-border-color);
              border-radius: 4px;
              height: 100%;

              .el-checkbox {
                margin-right: 20px;
                margin-bottom: 12px;
                text-align: left;
                width: 179px;
                height: 36px;
                line-height: 36px;
                background: var(--menuManage-checkbox-bgc);
                opacity: 0.9;
                border-radius: 6px;
                padding-left: 14px;
                float: left;
              }
            }

            .systemInput {
              margin-bottom: 12px;

              ~.el-checkbox-group {
                height: calc(100% - 44px);
              }
            }
          }
        }
      }
    }

    .params {
      margin-top: 12px;
    }
  }
}

.demo-input-suffix {
  display: flex;
  justify-content: space-around;
  line-height: 40px;

  label {
    flex: 4;
  }

  .el-input {
    flex: 8;
    width: 270px;
  }
}

.el-dialog {
  .el-input {
    width: 300px;
  }
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.scriptStatementsClass {
  height: 60vh;
  overflow: auto;
  display: flex;
  justify-content: space-between;
}

/deep/ .el-dialog__body {
  /* padding: 5px 15px; */
  padding-top: 0px;
  padding-bottom: 45px;
}

/deep/ .CodeMirror {
  height: 100%
}
</style>